import { injectable, inject,Container } from 'inversify';
import {
    AbstractViewContribution, FrontendApplication,
    FrontendApplicationContribution,
    WidgetFactory, WidgetManager, ApplicationShell
} from '@theia/core/lib/browser';
import {
    CommandContribution,
    CommandRegistry
} from '@theia/core/lib/common';
import { ToolsWidget } from './tools-widget';
import { ToolsCommands, TOOLS_WIDGET_FACTORY_ID } from '../common/tools-types';

@injectable()
export class ToolsViewContribution extends AbstractViewContribution<ToolsWidget> implements FrontendApplicationContribution {

    constructor() {
        super({
            widgetId: TOOLS_WIDGET_FACTORY_ID,
            widgetName: 'toolcollection',
            defaultWidgetOptions: {
                area: 'left',
                rank: 300
            },
            toggleCommandId: ToolsCommands.TOGGLE_TOOLS.id,
            // 设置图标的CSS类
            toggleKeybinding: 'ctrlcmd+shift+t'
        });
    }

     async initializeLayout(app: FrontendApplication): Promise<void> {
        console.log('ToolsViewContribution initializeLayout called');
        try {
            await this.openView({ activate: false, reveal: true });
            console.log('Tools view opened successfully');
        } catch (error) {
            console.error('Failed to open tools view:', error);
        }
    }
}

@injectable()
export class ToolsCommandContribution implements CommandContribution {

    constructor(
        @inject(ApplicationShell) private readonly shell: ApplicationShell,
        @inject(WidgetManager) private readonly widgetManager: WidgetManager
    ) {}

    registerCommands(registry: CommandRegistry): void {
        registry.registerCommand(ToolsCommands.TOGGLE_TOOLS, {
            execute: async () => {
                console.log('Toggle tools command executed');
                try {
                    const widget = await this.widgetManager.getOrCreateWidget(TOOLS_WIDGET_FACTORY_ID);
                    if (widget) {
                        console.log('Found widget:', widget.id);
                        this.shell.activateWidget(widget.id);
                    } else {
                        console.error('No widget found');
                    }
                } catch (error) {
                    console.error('Error in toggle command:', error);
                }
            }
        });
    }
}

